//
//  TLTweetPhotosView.m
//  Coding_iOS
//
//  Created by taolei-mac on 2017/11/24.
//  Copyright © 2017年 com.lianchuan. All rights reserved.
//

#import "TLTweetPhotosView.h"
#import "TLHtmlMediaItem.h"

#define TLTweetPhotosMaxCount 9
#define TLTweetPhotosMaxCols(photosCount) ((photosCount==4)?2:3)
#define TLTweetPhotoMargin 5.0
#define TLTweetPhotoW  (((TLScreenW - 2 * TLTweetPhotoMargin - 40) / 3))
#define TLTweetPhotoH TLTweetPhotoW

@implementation TLTweetPhotosView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self){
        
        for (int i = 0; i < TLTweetPhotosMaxCount; i++) {
            UIImageView *photoView = [[UIImageView alloc] init];
            photoView.tag = i;
            [self addSubview:photoView];
        }
    }
    return self;
}

- (void)setHtmlMedias:(NSArray *)htmlMedias
{
    _htmlMedias = htmlMedias;
    for (int i = 0; i < TLTweetPhotosMaxCount; i++ ) {
       
        UIImageView *photoView = self.subviews[i];
        if (i < htmlMedias.count) { // 显示图片
            TLHtmlMediaItem *media = htmlMedias[i];
            [photoView sd_setImageWithURL:[NSURL URLWithString:media.src] placeholderImage:[UIImage originImageWithName:@"placeholder_coding_square_55"]];
            photoView.hidden = NO;
            if(htmlMedias.count == 1){
                
            }
        } else { // 隐藏图片
            photoView.hidden = YES;
        }
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    int count = (int)self.htmlMedias.count;
    int maxCols = TLTweetPhotosMaxCols(count);
    for (int i = 0; i < count; i++) {
        
        UIImageView *photoView = self.subviews[i];
        photoView.width = TLTweetPhotoW;
        photoView.height = TLTweetPhotoH;
        photoView.x = (i % maxCols) * (TLTweetPhotoW + TLTweetPhotoMargin);
        photoView.y = (i / maxCols) * (TLTweetPhotoH + TLTweetPhotoMargin);
        if(count == 1){
           
            photoView.width = 225;
            photoView.height = 225;
            photoView.x = 0;
            photoView.y = 0;
        }
    }
}

- (CGSize)sizeWithHtmlMediaImageCount:(NSArray *)htmlMedias
{
    int count = (int)htmlMedias.count;
    int maxCols = TLTweetPhotosMaxCols(count);
    // 总列数
    int totalCols = count >= maxCols ?  maxCols : count;
    // 总行数
    int totalRows = (count + maxCols - 1) / maxCols;
    
    // 计算尺寸
    CGFloat photosW = totalCols * TLTweetPhotoW + (totalCols - 1) * TLTweetPhotoMargin;
    CGFloat photosH = totalRows * TLTweetPhotoH + (totalRows - 1) * TLTweetPhotoMargin;
    if(count == 1){
        photosW = 225;
        photosH = 225;
    }

    return CGSizeMake(photosW, photosH);
}

@end
